// KDRegister
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:lz_app_core/utils/kd_storage.dart';
import 'package:lz_base/kd_base.dart';
import 'package:lz_login/src/serve/kd_login_api.dart';
import 'package:lz_router/kd_router.dart';
import 'package:lz_ui/kd_ui.dart';
import 'package:lz_app_core/extension/kd_extension.dart';
import 'package:get/get.dart';
import '../../kd_login.dart';
import '../widgets/kd_pwd_warm_widget.dart';
import '../widgets/kd_verification_code.dart';

class KDForgetPwdPage extends StatefulWidget {
  const KDForgetPwdPage({super.key});

  @override
  State<KDForgetPwdPage> createState() => _KDForgetPwdPageState();
}

class _KDForgetPwdPageState extends State<KDForgetPwdPage> {
  /// obs
  var phoneErr = false.obs;
  var pwdWarmType = KDPwdWarmType.none.obs;
  var msgCodeErr = false.obs;

  /// 用户输入
  var phone = '';
  var hasGetCode = false;
  var code = '';
  bool checkProtocal = false;

  /// 密码
  final RxBool _pwdErr = false.obs;
  final Rx<KDPwdWarmType> _pwdWarmType = KDPwdWarmType.none.obs;
  String _pwd = '';

  /// 确认密码
  final RxBool _confirmPwdErr = false.obs;
  final Rx<KDPwdWarmType> _confirmPwdWarmType = KDPwdWarmType.none.obs;
  String _confirmPwd = '';

  /// 输入手机号码
  late final TextEditingController _phoneController = TextEditingController();
  @override
  void initState() {
    super.initState();
    if (Get.arguments is Map<String, String>) {
      phone = Get.arguments["phone"] ?? "";
      _phoneController.text = phone;
    }
  }

  @override
  Widget build(BuildContext context) {
    return KDScaffold.scaffold(
      title: "忘记密码",
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.all(KD.size(32)),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "手机号",
                style:
                    TextStyle(color: Color(0xFF1D2129), fontSize: KD.font(32)),
              ),

              _space(),

              Obx(
                () => KDFormInputWidget(
                  error: "请输入正确手机号",
                  isErr: phoneErr.value,
                  child: Row(
                    children: [
                      Expanded(
                          child: KDTextFiled.aLineInput(
                              controller: _phoneController,
                              maxLength: 11,
                              keyboardType: TextInputType.number,
                              key: const ObjectKey('phone'),
                              onChanged: (e) {
                                phone = e;
                                if (e.length == 11 && !e.isPhoneNumber) {
                                  phoneErr.value = true;
                                } else {
                                  phoneErr.value = false;
                                }
                              },
                              clearButtonMode: OverlayVisibilityMode.editing)),
                    ],
                  ),
                ),
              ),

              /// 验证码
              KDVerificationCodeWidget(
                phoneCall: () => phone,
                hasGetCode: (p0) => hasGetCode = p0,
                type: 2,
                inputCode: (p0) {
                  code = p0;
                },
              ),
              Obx(
                () => KDAccountPwdWidget(
                  title: "密码",
                  error: _pwd.length < 6
                      ? "密码长度需6-20位"
                      : "请输入大于10位数密码或使用数字、字母、特殊字符号组合",
                  isErr: _pwdErr.value,
                  isPwd: true,
                  errorWidget: _pwdErr.value
                      ? null
                      : Obx(() => KDPwdWarmWidget(_pwdWarmType.value)),
                  onChange: KDInputDebounce((e) {
                    _pwd = e;

                    if (_pwd.length >= 6) {
                      _pwdErr.value = false;
                      _pwdWarmType.value = KDPwdWarmType.getType(_pwd);
                    } else {
                      _pwdErr.value = false;
                      _pwdWarmType.value = KDPwdWarmType.none;
                    }
                  }, 100),
                ),
              ),
              Obx(
                () => KDAccountPwdWidget(
                  title: "确认密码",
                  error: _confirmPwd.length < 6
                      ? "密码长度需6-20位"
                      : "请输入大于10位数密码或使用数字、字母、特殊字符号组合",
                  isErr: _confirmPwdErr.value,
                  isPwd: true,
                  errorWidget: _confirmPwdErr.value
                      ? null
                      : Obx(() => KDPwdWarmWidget(_confirmPwdWarmType.value)),
                  onChange: KDInputDebounce((e) {
                    _confirmPwd = e;

                    if (_pwd.length >= 6) {
                      _confirmPwdErr.value = false;
                      _confirmPwdWarmType.value =
                          KDPwdWarmType.getType(_confirmPwd);
                    } else {
                      _confirmPwdErr.value = false;
                      _confirmPwdWarmType.value = KDPwdWarmType.none;
                    }
                  }, 100),
                ),
              ),

              /// 下一步
              KDBgWidget(
                bgColor: KDColor.main,
                margin: EdgeInsets.zero,
                height: KD.size(80),
                onTap: () {
                  next();
                },
                child: Center(
                    child: Text(
                  "完成",
                  style: TextStyle(color: Colors.white, fontSize: KD.font(32)),
                )),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 按照dp
  Widget _space({double height = 16}) => SizedBox(
        height: KD.size(height),
      );

  next() async {
    if (!phone.isPhone) {
      phoneErr.value = true;
    }

    if (!hasGetCode) {
      DialogUtils.showToast("请先获取验证码");
      return;
    }

    if (hasGetCode && code.isEmpty) {
      DialogUtils.showToast("请先输入验证码");
      return;
    }

    if (hasGetCode && code.length != 4) {
      DialogUtils.showToast("验证码有误");
      return;
    }

    if (_pwd.length < 6 || _pwdWarmType.value == KDPwdWarmType.weak) {
      _pwdErr.value = true;
      return;
    }

    if (_confirmPwd.length < 6 ||
        _confirmPwdWarmType.value == KDPwdWarmType.weak) {
      _confirmPwdErr.value = true;
      return;
    }
    _confirmPwdErr.value = false;
    _pwdErr.value = false;

    if (_pwd != _confirmPwd) {
      DialogUtils.showToast("两次密码不一致！");
      return;
    }

    bool success = await KDLoginApi.forgotPwdFirst(phone: phone, captcha: code);
    if (!success) {
      return;
    }

    bool saveSuccess = await KDLoginApi.forgotPwdSave(
        phone: phone, captcha: code, password: _pwd);
    if (saveSuccess) {
      KDStorage.save(KDStorageKey.phone.name, phone);
      KDStorage.save(KDStorageKey.pwd.name, _pwd);
      backLogin();
    }
  }

  backLogin() {
    KDAlert.alertWidget(
      barrierDismissible: false,
      actionType: const KDAlertActionType.close("知道了"),
      content: "登录密码修改成功请您重新登录",
      contentColor: KDColor.title,
      close: () {
        Future.delayed(const Duration(milliseconds: 200))
            .then((value) => KDRouter.offAllNamed(KDLoginRouter.login));
      },
    );
  }
}
